#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
京东配送回调SDK使用示例 - Python版本
"""

import sys
import os
from decimal import Decimal

# 添加上级目录到路径，以便导入SDK
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from jingdong_callback_sdk import JingdongCallbackSDK, Order, OrderFee


def main():
    """主函数"""
    
    # 初始化SDK
    sdk = JingdongCallbackSDK(
        developer_id='your-developer-id',      # 海博技术服务平台分配的开发者ID
        secret='your-secret',                  # 签名密钥
        environment='test',                    # 环境: test, sandbox, prod
        redis_config={                         # Redis配置（可选，用于防重复）
            'host': '127.0.0.1',
            'port': 6379,
            'db': 0,
            'password': '',                    # 如果Redis有密码
        },
        enable_log=True,                       # 启用日志
        user_agent='MyApp-JingdongSDK/1.0',   # 自定义User-Agent
        timeout=120,                           # 请求超时时间（秒）
        max_retry=3                           # 最大重试次数
    )
    
    try:
        # 示例1：基本状态回调
        print("=== 示例1：基本状态回调 ===")
        basic_status_callback(sdk)
        
        print()
        
        # 示例2：包含额外参数的状态回调
        print("=== 示例2：包含额外参数的状态回调 ===")
        status_callback_with_extra_params(sdk)
        
        print()
        
        # 示例3：取消订单回调
        print("=== 示例3：取消订单回调 ===")
        cancel_order_callback(sdk)
        
        print()
        
        # 示例4：转单回调
        print("=== 示例4：转单回调 ===")
        transfer_order_callback(sdk)
        
        print()
        
        # 示例5：包含费用信息的完成回调
        print("=== 示例5：包含费用信息的完成回调 ===")
        completed_order_with_fee_callback(sdk)
        
        print()
        
        # 示例6：连通性测试
        print("=== 示例6：连通性测试 ===")
        connectivity_test(sdk)
        
        print()
        
        # 示例7：状态转换工具
        print("=== 示例7：状态转换工具 ===")
        status_conversion_demo()
        
        print()
        
        # 示例8：取消原因码工具
        print("=== 示例8：取消原因码工具 ===")
        cancel_reason_code_demo()
        
    finally:
        # 关闭SDK资源
        sdk.close()
    
    print("\n示例运行完成！")


def basic_status_callback(sdk):
    """示例1：基本状态回调"""
    # 创建订单对象
    order = Order(
        id=12345,
        platform_order_no='JD202312345678',
        order_no='ORDER_20231201_001',
        jd_store_id='STORE_001',
        carrier_merchant_id='HBT_JZD',
        rider_id=1001,
        rider_name='张三',
        rider_phone='13800138000',
        rider_lng=116.397128,
        rider_lat=39.916527
    )
    
    # 发送"已接单"状态回调
    result = sdk.send_status_callback(order, 20)
    
    if result.success:
        print("✅ 状态回调发送成功")
        print(f"响应数据: {result.data}")
    else:
        print(f"❌ 状态回调发送失败: {result.message}")


def status_callback_with_extra_params(sdk):
    """示例2：包含额外参数的状态回调"""
    order = create_sample_order()
    
    extra_params = {
        'riderLng': 116.407526,        # 实时骑手经度
        'riderLat': 39.904030,         # 实时骑手纬度
        'orderImages': {               # 订单图片
            'pickup': [
                'https://example.com/image1.jpg',
                'https://example.com/image2.jpg'
            ]
        }
    }
    
    # 发送"已取货"状态回调
    result = sdk.send_status_callback(order, 30, extra_params)
    
    if result.success:
        print("✅ 已取货状态回调发送成功")
    else:
        print(f"❌ 已取货状态回调发送失败: {result.message}")


def cancel_order_callback(sdk):
    """示例3：取消订单回调"""
    order = create_sample_order()
    
    cancel_params = {
        'cancelReasonCode': JingdongCallbackSDK.get_cancel_reason_code('CUSTOMER'),
        'cancelReasonDesc': JingdongCallbackSDK.get_cancel_reason_desc('CUSTOMER', '用户临时有事'),
        'cancelFee': 5.00
    }
    
    # 发送取消状态回调
    result = sdk.send_status_callback(order, 99, cancel_params)
    
    if result.success:
        print("✅ 取消订单回调发送成功")
    else:
        print(f"❌ 取消订单回调发送失败: {result.message}")


def transfer_order_callback(sdk):
    """示例4：转单回调"""
    order = create_sample_order()
    
    transfer_params = {
        'isTransfer': True,
        'oldRiderId': 1001,
        'newRiderId': 1002,
        'newRiderName': '李四',
        'newRiderPhone': '13900139000',
        'transferReason': '骑手临时有事转单'
    }
    
    # 发送转单后的"已接单"状态回调
    result = sdk.send_status_callback(order, 20, transfer_params)
    
    if result.success:
        print("✅ 转单回调发送成功")
    else:
        print(f"❌ 转单回调发送失败: {result.message}")


def completed_order_with_fee_callback(sdk):
    """示例5：包含费用信息的完成回调"""
    order = create_sample_order()
    
    # 设置费用信息
    order.fee = OrderFee(
        actual_amount=Decimal('15.80'),
        toll_fee=Decimal('2.00'),
        waiting_fee=Decimal('1.00'),
        parking_fee=Decimal('0.50')
    )
    
    # 发送"已送达"状态回调
    result = sdk.send_status_callback(order, 50)
    
    if result.success:
        print("✅ 已送达回调发送成功")
    else:
        print(f"❌ 已送达回调发送失败: {result.message}")


def connectivity_test(sdk):
    """示例6：连通性测试"""
    connectivity = sdk.test_connectivity()
    
    # DNS解析测试
    dns = connectivity.dns
    print(f"DNS解析: {'✅ 成功' if dns.success else '❌ 失败'}")
    print(f"  主机: {dns.host} => {dns.ip}")
    
    # 端口连通性测试
    port = connectivity.port
    print(f"端口连通: {'✅ 成功' if port.success else '❌ 失败'}")
    print(f"  端口: {port.host}:{port.port}")
    if not port.success and port.error:
        print(f"  错误: {port.error}")
    
    # HTTP请求测试
    http = connectivity.http
    print(f"HTTP请求: {'✅ 成功' if http.success else '❌ 失败'}")
    print(f"  状态码: {http.http_code}")
    if not http.success and http.error:
        print(f"  错误: {http.error}")


def status_conversion_demo():
    """示例7：状态转换工具"""
    local_statuses = ['0', '10', '20', '25', '30', '40', '50', '99']
    
    for local_status in local_statuses:
        jd_status = JingdongCallbackSDK.convert_local_status_to_jingdong_status(local_status)
        print(f"本地状态 {local_status} => 京东状态 {jd_status}")


def cancel_reason_code_demo():
    """示例8：取消原因码工具"""
    roles = ['ADMIN', 'MERCHANT', 'CUSTOMER', 'SYSTEM', 'RIDER', 'CARRIER']
    
    for role in roles:
        reason_code = JingdongCallbackSDK.get_cancel_reason_code(role)
        reason_desc = JingdongCallbackSDK.get_cancel_reason_desc(role)
        print(f"角色 {role} => 取消码 {reason_code} ({reason_desc})")


def create_sample_order():
    """创建示例订单"""
    return Order(
        id=12345,
        platform_order_no='JD202312345678',
        order_no='ORDER_20231201_001',
        jd_store_id='STORE_001',
        carrier_merchant_id='HBT_JZD',
        rider_id=1001,
        rider_name='张三',
        rider_phone='13800138000',
        rider_lng=116.397128,
        rider_lat=39.916527
    )


def demo_with_dict():
    """使用字典格式的订单信息示例"""
    print("=== 使用字典格式的订单信息 ===")
    
    # 初始化SDK
    sdk = JingdongCallbackSDK(
        developer_id='your-developer-id',
        secret='your-secret',
        environment='test'
    )
    
    try:
        # 使用字典格式的订单信息
        order_dict = {
            'id': 12345,
            'platform_order_no': 'JD202312345678',
            'order_no': 'ORDER_20231201_001',
            'jd_store_id': 'STORE_001',
            'carrier_merchant_id': 'HBT_JZD',
            'rider_id': 1001,
            'rider_name': '张三',
            'rider_phone': '13800138000',
            'rider_lng': 116.397128,
            'rider_lat': 39.916527
        }
        
        # 发送状态回调
        result = sdk.send_status_callback(order_dict, 20)
        
        if result.success:
            print("✅ 字典格式订单回调发送成功")
        else:
            print(f"❌ 字典格式订单回调发送失败: {result.message}")
            
    finally:
        sdk.close()


def demo_error_handling():
    """错误处理示例"""
    print("=== 错误处理示例 ===")
    
    # 使用错误的配置
    sdk = JingdongCallbackSDK(
        developer_id='wrong-developer-id',
        secret='wrong-secret',
        environment='test'
    )
    
    try:
        order = create_sample_order()
        result = sdk.send_status_callback(order, 20)
        
        if result.success:
            print("✅ 回调成功")
        else:
            print(f"❌ 回调失败: {result.message}")
            
            # 检查是否是防重复跳过
            if result.deduplicated:
                print("由于防重复机制跳过发送")
        
    except Exception as e:
        print(f"❌ 发生异常: {e}")
        
    finally:
        sdk.close()


if __name__ == '__main__':
    main()
    
    # 运行额外示例
    print("\n" + "="*50)
    demo_with_dict()
    
    print("\n" + "="*50)
    demo_error_handling()
